<template>
  <el-dialog title="选择用户" width="450px" :visible.sync="params.visible">
    <el-tabs v-model="activeTab">
      <el-tab-pane name="selectUser" label="选择用户">
        <compTree
          ref="tree1"
          :show-search="false"
          :tree-data="treeData1"
          :comp-tree-height="350"
          :tree-show-checkbox="params.ismutil"
          :tree-default-expanded-keys="treeDefaultCheckedKeys1"
          :tree-default-checked-keys="treeDefaultCheckedKeys1"
        />
      </el-tab-pane>
      <el-tab-pane name="scheme" label="选择方案">
        <compTree
          ref="tree2"
          :show-search="false"
          :tree-data="treeData2"
          :comp-tree-height="350"
          :tree-show-checkbox="params.ismutil"
          :tree-default-expanded-keys="treeDefaultCheckedKeys2"
          :tree-default-checked-keys="treeDefaultCheckedKeys2"
        />
      </el-tab-pane>
    </el-tabs>
    <div class="checkbox-div">
      <el-checkbox v-if="show1" v-model="returnName" style="margin-top: 10px">
        返回用户名
        <span style="color: #409eff">(微信发送为必选) </span>
      </el-checkbox>
      <el-checkbox v-if="show2" v-model="sendExecBy">
        发送给流程执行人
      </el-checkbox>
    </div>
    <dialog-btn slot="footer">
      <el-button
        v-if="activeTab === 'selectUser'"
        class="pull-left"
        type="primary"
        @click="savePlan"
      >
        另存为方案
      </el-button>
    </dialog-btn>

    <!-- //另存为方案弹窗 -->
    <show-plan-config-name-layer
      v-if="showPlanConfigNameLayerParams.visible"
      :params="showPlanConfigNameLayerParams"
    />
  </el-dialog>
</template>

<script>
/**
 * inData: { sID, sName, iType, isNullSelect, showToFlowBy(可选) }
 */
import { ParamArr, SQLTable } from '@/../public/js/paramarr'
import Global from '@/../public/js/global'
import { addPlanInfo, getPlanList } from '@/api/user'
import ShowPlanConfigNameLayer from './ShowPlanConfigNameLayer.vue'
import { getUserList } from '@/api/event'
export default {
  name: 'SelectUserPlanLayer',
  components: { ShowPlanConfigNameLayer },
  props: {
    params: {
      type: Object,
      default: () => {
        return {
          visible: true, // 是否显示当前窗口
          sID: '', // 传入的值
          sName: '', // 传入的值
          iType: '', // 传入的值
          iTabName: 'selectUser', // 传入的是哪个el-tab
          isNullSelect: false, // 是否可以选空的
          ismutil: false // 是否可以多选
        }
      }
    }
  },
  data() {
    return {
      activeTab: 'selectUser',
      treeData1: [],
      treeData2: [],
      returnName: false,
      sendExecBy: false,
      show1: false,
      show2: false,
      data: {}, // 接收入参
      g_lastActivePlan: '',
      treeDefaultCheckedKeys1: [],
      treeDefaultCheckedKeys2: [],
      // 方案另存为弹窗
      showPlanConfigNameLayerParams: {
        visible: false
      }
    }
  },
  created() {
    this.data = this.params
    this.activeTab = this.params.iTabName || 'selectUser'
    this.data.sID = this.data.sID || ''
    this.data.sName = this.data.sName || ''
    this.initWindow()
  },
  methods: {
    initWindow() {
      if (this.data.showToFlowBy) this.show2 = true
      if (this.data.iType === 1) {
        this.show1 = false
      }
      if (this.data.iType === 2 || this.data.iType === 3) {
        this.show1 = true
        if (this.data.sID === '') this.returnName = true
      }
      if (this.data.sID && this.data.sID.indexOf('[方案]') !== -1) {
        this.g_lastActivePlan = true
        this.activeTab = 'scheme'
      }
      if (this.data.sID.indexOf('{流程执行用户}') !== -1) {
        this.sendExecBy = true
      } else {
        this.sendExecBy = false
      }
      getUserList(new ParamArr()).then((vPar) => {
        this.lpfInitUser(vPar)
      })
      getPlanList(new ParamArr()).then((vPar) => {
        this.lpfInitPlan(vPar)
      })
    },
    lpfInitUser(vPar) {
      const nodes = []
      const nodeMap = new Map()
      // 分组
      let table = new SQLTable(vPar.getTable('QryGroup'))
      table.first()
      while (!table.eof()) {
        const node = {}
        node['id'] = table.getValueByName('ID')
        node.pid = table.getValueByName('PID')
        node['loginid'] = node.id
        node['name'] = table.getValueByName('Name')
        node['text'] = node.name
        node['icon'] = 'wenjianyi'
        node.folder = true
        var pnode = Global.getTreeviewPNode(nodeMap, nodes, node.pid)
        pnode.push(node)
        nodeMap.set(node.id, node)
        table.next()
      }
      table = new SQLTable(vPar.getTable('QryUser'))
      table.first()
      while (!table.eof()) {
        const node = {}
        node.id = table.getValueByName('ID')
        node.pid = table.getValueByName('PID')
        node['text'] = table.getValueByName('UserName')
        node['icon'] = 'jiaose'
        node['name'] = table.getValueByName('UserName')
        node['loginid'] = node.id
        node['userid'] = table.getValueByName('UserID')
        node['mail'] = table.getValueByName('EMail')
        node['mobile'] = table.getValueByName('Mobile')
        node['folder'] = false
        let isCheck = false
        if (!this.g_lastActivePlan) {
          if (this.data.iType === 0) {
            isCheck = this.data.sID.indexOf(node.loginid) !== -1
          } else if (this.data.iType === 1) {
            isCheck = this.data.sID.indexOf(node.userid) !== -1
          } else if (this.data.iType === 2) {
            isCheck = this.isCheckNode(node.mail, node.userid)
          } else if (this.data.iType === 3) {
            isCheck = this.isCheckNode(node.mobile, node.userid)
          }
        }
        if (isCheck) {
          this.treeDefaultCheckedKeys1.push(node.id)
        }
        pnode = Global.getTreeviewPNode(nodeMap, nodes, node.pid)
        pnode.push(node)
        nodeMap.set(node.id, node)
        table.next()
      }
      this.treeData1 = nodes
    },
    lpfInitPlan(vPar) {
      const nodes = []
      const table = new SQLTable(vPar.getTable('k_target_plan'))
      const idArr = this.data.sID
        .replace(/(\[方案\])|(\{流程执行用户\})/g, '')
        .split(',')
      const nodeMap = new Map()
      table.first()
      while (!table.eof()) {
        const node = {}
        node.id = table.getValueByName('ID')
        node.pid = table.getValueByName('PID')
        node['name'] = table.getValueByName('Name')
        node.folder = table.getValueByName('Type') === '0'
        node.state = {}
        if (node.folder) {
          node['text'] = node.name
          node['icon'] = 'wenjianyi'
        } else {
          node['text'] = node.name
          node['icon'] = 'jiaose'
        }
        if (this.g_lastActivePlan && idArr.indexOf(node.id) !== -1) {
          this.treeDefaultCheckedKeys2.push(node.id)
        }
        const pnode = Global.getTreeviewPNode(nodeMap, nodes, node.pid)
        pnode.push(node)
        nodeMap.set(node.id, node)
        table.next()
      }
      this.treeData2 = nodes
      if (this.data.sName !== '' && this.data.sName.slice(0, 4) === '[方案]') {
        this.activeTab = 'scheme'
      }
    },
    isCheckNode(s, userid) {
      let isCheck = false
      if (!userid) return isCheck
      const idArr = (this.data.sID || '').split(',')
      if (s !== '') isCheck = idArr.indexOf(s) !== -1
      if (!isCheck) {
        isCheck = idArr.indexOf(userid) !== -1
        if (isCheck && !this.returnName) this.returnName = true
      }
      return isCheck
    },
    savePlan() {
      const nodes = this.$refs.tree1.getCheckedNodes()
      if (nodes.length === 0) return this.$message.warning('请选择用户')
      const ids = []
      const names = []
      for (let i = 0; i < nodes.length; i++) {
        if (!nodes[i].folder) {
          ids.push(nodes[i].loginid)
          names.push(nodes[i].name)
        }
      }
      const dialog = this.showPlanConfigNameLayerParams
      dialog.confirm = (params) => {
        var vPar = new ParamArr()
        vPar.setStr('LoginIDs', ids.join(','))
        vPar.setStr('LoginNames', names.join(','))
        vPar.setStr('Name', params.sNames)
        vPar.setBool('Enable', true)
        vPar.setBool('NoMsg', params.isMsg)
        vPar.setBool('NoWeChat', params.isWeChat)
        addPlanInfo(vPar).then((vPar) => {
          getPlanList(vPar)
            .then((vPar) => {
              this.lpfInitPlan(vPar)
              dialog.visible = false
            })
        })
      }
      dialog.visible = true
    },
    confirm() {
      const ids = []
      const names = []
      let resStr = this.sendExecBy ? '{流程执行用户},' : ''
      if (this.activeTab === 'selectUser') {
        const nodes = this.$refs.tree1.getCheckedNodes()
        for (let i = 0; i < nodes.length; i++) {
          if (!nodes[i].folder) {
            this.setParamValue(ids, names, nodes[i], this.returnName)
          }
        }
        if (this.data.isNullSelect && ids.length === 0) {
          return this.$message.warning('请选择用户')
        }
      } else {
        const nodes = this.$refs.tree2.getCheckedNodes()
        for (let i = 0; i < nodes.length; i++) {
          const node = nodes[i]
          if (!node.folder) {
            ids.push(node.id)
            names.push(node.name)
          }
        }
        if (ids.length !== 0 || (this.data.isNullSelect && resStr)) {
          resStr = '[方案]' + resStr
        } else if (this.data.isNullSelect) {
          // 没有选择节点时候弹出提示
          return this.$message.warning('请选择方案')
        }
      }
      if (ids.length === 0 && resStr) {
        resStr = resStr.substring(0, resStr.length - 1)
      }
      this.params.confirm({
        sID: resStr + ids.join(','),
        sName: resStr + names.join(','),
        sTab: this.activeTab
      })
    },
    setParamValue(ids, names, node, returnUserName) {
      switch (parseInt(this.data.iType)) {
        case 0 /* rtLoginID*/:
          ids.push(node.loginid)
          names.push(node.name)
          break
        case 1 /* rtUser*/:
          ids.push(node.id)
          names.push(node.name)
          break
        case 2 /* rtMail*/:
          if (returnUserName) {
            ids.push(node.userid)
            names.push(node.name)
          } else if (node.mail !== '') {
            ids.push(node.mail)
            names.push(node.name)
          }
          break
        case 3 /* rtMobile\WeChat*/:
          if (returnUserName) {
            ids.push(node.userid)
            names.push(node.name)
          } else if (node.mobile !== '') {
            ids.push(node.mobile)
            names.push(node.name)
          }
          break
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.checkbox-div ::v-deep {
  .el-checkbox__input {
    transform: translateY(-1px);
    font-size: 12px;
  }
  .el-checkbox__label {
    font-size: 12px;
    padding-left: 3px;
    margin-right: 10px;
  }
}
</style>
